package com.dapeis.web.wx.controller.impl;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import me.chanjar.weixin.common.util.StringUtils;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ag.web.controller.BaseController;
import com.dapeis.core.utils.StylistConstants;

/**
 * 微信后台通知
 * Title:WxNotifyController.java WxNotifyController
 * Description:
 * @author yuanyong
 * @date 2017年4月18日 下午1:43:15 
 * Email: hzyuanyong@126.com
 *
 */
@Controller
@RequestMapping("/wx/notify")
public class WxNotifyController extends BaseController {
	
	@Resource WxMpService wxMpService;
	@Resource WxMpMessageRouter wxMpMessageRouter;
	
	@RequestMapping(produces = StylistConstants.ContentType.TEXT_HTML)
	public @ResponseBody String execute(HttpSession session, HttpServletRequest request) throws IOException {
		print(request);
			
	    String signature = request.getParameter("signature");
	    String nonce = request.getParameter("nonce");
	    String timestamp = request.getParameter("timestamp");

	    if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
	      // 消息签名不正确，说明不是公众平台发过来的消息
	    	logger.error("微信通知验签失败: requestUrl={}, timestamp={}, nonce={}, signature={}, ",new Object[] {
					request.getRequestURI(),
					timestamp,
					nonce,
					signature
				});
	      return "非法请求";
	    }

	    String echostr = request.getParameter("echostr");
	    if (StringUtils.isNotBlank(echostr)) {
	      // 说明是一个仅仅用来验证的请求，回显echostr
	      return echostr;
	    }

	    String encryptType = StringUtils.isBlank(request.getParameter("encrypt_type")) ? "raw" : request.getParameter("encrypt_type");

	    if ("raw".equals(encryptType)) {
	      // 明文传输的消息
	      WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
	      WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
	      if (outMessage != null) {
	        return outMessage.toXml();
	      }
	      return "";
	    }

	    if ("aes".equals(encryptType)) {
	      // 是aes加密的消息
	      String msgSignature = request.getParameter("msg_signature");
	      WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(request.getInputStream(), wxMpService.getWxMpConfigStorage(), timestamp, nonce, msgSignature);
	      WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
	      
	      if (outMessage != null) {
	    	  return outMessage.toEncryptedXml(wxMpService.getWxMpConfigStorage());
	      }
	      return "";
	    }

		return "不可识别的加密类型";
	}
}